<template lang="pug">
.flex.gap-4.items-center.mb-4.justify-between
  view.label.text-prim.text-right.pr-2 {{props.comInfo.label}}
  .add-btn(v-if="pickedGongyi") {{pickedGongyi.name}}
  .add-btn(v-else @click="openGongyiPopup" ) 选择工艺
uni-popup(ref="gongyiPopup" type="bottom") 
  .popup-bottom
    .flex.font-medium.mb-8.text-base.justify-between
      .flex-1 添加工艺
      uni-icons(type="closeempty"  color="dedede" size="24" @click.stop="closeGongyiPopup()")
    .flex
      view
        .list-btn(v-for="(item,i) in gongyiList" :key='item.id' @click="gongyiColsChange(i)"
        :class="{'selected':(item===gongyiSubSelect)}") 
          .content {{item.name}}
      .list-row
          .w-full.grid.grid-cols-2.gap-2
            template(v-if="gongyiSubSelect && gongyiSubSelect.sub")
              .goods-card(v-for="item in gongyiSubSelect.sub" :key="'sub'+item.id" @click="gongyiPickerChange(item)"
                :class="{'selected':(gongyiPickerSelect===item)}")
                view.mb-2(class="h-[20vw] w-[23vw]")
                  //- image.w-full.h-full(:src="item.pic" mode="aspectFit")
                .title {{item.name}}
    .flex.justify-end.mt-8.mb-16
      button.submit-btn.w-32(@click="submitGongyi") 确定
</template>
<script setup>
import {  selectProductMaterialWithDetail  } from "@/api/common.js";

const props =  defineProps({
  comInfo:Object,
})
const emit = defineEmits(["change"])

const pickedGongyi = ref(null)
const gongyiList = ref([]);

onMounted(()=>{  
  const page = getCurrentPages();
  let crrt = page[page.length-1];
  getData(crrt.options.id,props.comInfo.materialType);

})
async function getData(id,materialType){ // 工艺
  const res = await selectProductMaterialWithDetail({
    productId:id,
    materialType:materialType,
    
  })
  gongyiList.value = res.rows;
  gongyiColsChange(0);


  let flat = [];
  let defaultId =  props.comInfo.value;
  for(let item of gongyiList.value){
    flat.push(...item.sub)
  }
  let defaultVal = flat.find(el=>el.id==defaultId);
  if(defaultVal){
    pickedGongyi.value = defaultVal;
  }
}
// ==== gongi pop start ==== 
const gongyiPopup = ref(null)
async function openGongyiPopup () {
  gongyiPopup.value.open();
}
function closeGongyiPopup () {
  gongyiPopup.value.close();
}
const gongyiPickerSelect = ref(null);
const gongyiSubSelect = ref(null)
function gongyiColsChange(index){
  gongyiSubSelect.value = gongyiList.value[index]
}

function gongyiPickerChange (item) {
  gongyiPickerSelect.value = item;
}
function submitGongyi(){
  pickedGongyi.value  = gongyiPickerSelect.value;
  closeGongyiPopup();
  gongyiPickerSelect.value = gongyiList.value[0];
  gongyiSubSelect.value=null;
  emit("change",pickedGongyi.value)
}
 
</script>
<style scoped lang="scss">
@import  "./style.scss";
</style>